package com.liliudong.cursormate.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liliudong.cursormate.entity.SysRole;
import com.liliudong.cursormate.entity.SysUserRole;
import com.liliudong.cursormate.mapper.SysRoleMapper;
import com.liliudong.cursormate.mapper.SysUserRoleMapper;
import com.liliudong.cursormate.service.SysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @author Liudong.li
 * @description 针对表【sys_user_role(系统用户角色关联表)】的数据库操作Service实现
 * @createDate 2023-10-24 22:29:24
 */
@Service
@RequiredArgsConstructor
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole>
        implements SysUserRoleService {

    private final SysRoleMapper sysRoleMapper;

    @Override
    @Transactional
    public void saveBatchByUserId(Long userId, List<String> roleCodeList) {
        List<SysRole> sysRoles = sysRoleMapper.selectList(
                Wrappers.lambdaQuery(SysRole.class)
                        .select(SysRole::getId, SysRole::getRoleCode)
                        .in(SysRole::getRoleCode, roleCodeList)
        );
        List<SysUserRole> sysUserRoles = roleCodeList.stream()
                .map(roleCode -> {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(userId);
                    sysRoles.stream()
                            .filter(sysRole -> Objects.equals(sysRole.getRoleCode(), roleCode))
                            .findAny()
                            .ifPresent(sysRole -> sysUserRole.setRoleId(sysRole.getId()));
                    sysUserRole.setRoleCode(roleCode);
                    return sysUserRole;
                }).collect(Collectors.toList());
        this.saveBatch(sysUserRoles);
    }

    @Override
    public void removeByUserId(Long userId) {
        baseMapper.delete(
                Wrappers.lambdaQuery(SysUserRole.class)
                        .eq(SysUserRole::getUserId, userId)
        );
    }

    @Override
    public List<String> listRoleCodeListByUserId(Long userId) {
        List<SysUserRole> sysUserRoles = baseMapper.selectList(
                Wrappers.lambdaQuery(SysUserRole.class)
                        .select(SysUserRole::getRoleCode)
                        .eq(SysUserRole::getUserId, userId)
        );
        return sysUserRoles.stream()
                .map(SysUserRole::getRoleCode)
                .collect(Collectors.toList());
    }
}




